<style lang="less">
    @import '../../styles/common.less';
    .previewcss h1{
        text-align: center;
        font-size: 14px;
        font-weight: 600;
        margin-top: 20px
    }
    .ivu-col-offset-5 {
        margin: auto
    }
</style>

<template>
    <div>
        <Row>
            <Col span="24">
                <Card>
                    <Form >
                        <!-- <FormItem label="轮播图片" >
                            <div class="demo-upload-list" v-if="coverImageUrl" style="width:120px;line-height:0px;margin-left:40px">
                                <div style="width:100%">
                                    <img :src="coverImageUrl">
                                </div>
                                <div class="demo-upload-list-cover" style="bottom:0">
                                    <Icon type="ios-eye-outline" @click.native="handleView(item)"></Icon>
                                    <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                                </div>
                            </div>
                            <Upload 
                                :action="actionName"
                                ref="upload"
                                :show-upload-list="false"
                                :default-file-list="defaultList"
                                :on-success="handleSuccess"
                                :format="['jpg','jpeg','png']"
                                :max-size="10240"
                                :on-format-error="handleFormatError"
                                :on-exceeded-size="handleMaxSize"
                                :before-upload="handleBeforeUpload"
                                multiple
                                style="width:100px;border:none;margin-left:52px"
                            >
                                <Button icon="ios-camera">选择图片</Button>
                            </Upload>
                        </FormItem> -->
                        <FormItem >
                            <RadioGroup v-model="articleSource">
                                <Radio label="商品详情页"></Radio>
                                <Radio label="商品组"></Radio>
                                <Radio label="自定义内容"></Radio>
                                <Radio label="外部网页链接"></Radio>
                            </RadioGroup>
                        </FormItem>
                        <FormItem >
                        <Row type="flex" justify="start" v-show="articleSource=='商品组'">
                            <Col span="20">
                            <FormItem label="商品组">
                                <Select clearable v-model="groupUuid" style="width:250px">
                                <Option v-bind:key="group.groupUuid" :value="group.groupUuid" v-for="group in groups">
                                    {{group.groupName}}
                                </Option>
                                </Select>
                            </FormItem>
                            </Col>
                        </Row>
                        </FormItem>
                        <FormItem  v-show="articleSource=='商品详情页'">
                        <Row>
                            <Col span="24">
                                <Row type="flex" justify="start">
                                <Col span="10">
                                    <FormItem label="选择商品">
                                    <Select
                                        v-model="groupBuyProductUuid"
                                        filterable
                                        remote
                                        :remote-method="searchProduct"
                                        placeholder="输入关键字搜索商品"
                                    >
                                        <Option
                                        v-for="(option, index) in products"
                                        :value="option.groupBuyProductUuid"
                                        :label="option.productDTO.productName"
                                        :key="option.groupBuyProductUuid"
                                        >{{option.productDTO.productName}}</Option>
                                    </Select>
                                    </FormItem>
                                </Col>
                                </Row>
                            </Col>
                        </Row>
                        </FormItem>
                        <FormItem label="外部网页链接" v-show="articleSource=='外部网页链接'">
                            <Input v-model="previewUrl"></Input>
                        </FormItem>
                    </Form>
                    <div class="margin-top-20" v-show="articleSource=='自定义内容'">
                        <textarea id="articleEditor"></textarea>
                    </div>
                    <Modal title="封面图片" v-model="visible">
                        <img :src="coverImageUrl" v-if="visible" style="width: 100%">
                    </Modal>
                </Card>
            </Col>

        </Row>
        <Row class="margin-top-10">
        <Button type="primary" @click.native="save()" :loading="loading">保存</Button>
        </Row>
    </div>
</template>

<script>
import tinymce from 'tinymce';
export default {
    name: 'artical-publish',
    data () {
        return {
            searchProductName:'',
            pageSize: 15,
            startIndex: 0,
            swiper:{},
            groupUuid:'',   //商品详情ID
            products:[],
            groups: [], //商品组列表
            groupBuyProductUuid:'', //商品详情
            showMateria:false,
            materias:[],
            timestamp:'1971-01-01 00:00',
            previewCopywriting:false,
            uploadList: [],
            loading:false,
            actionName:this.$http.defaults.baseURL+'admin/uploadMediaFile',
            articleUuid:'',
            swiper:'',
            coverImageUrl:'',
            visible:false,
            defaultList:[],
            editModel:false,
            articleTitle: '',
            articleError: '',
            showLink: false,
            fixedLink: '',
            articlePath: '',
            content1:'',
            articlePathHasEdited: false,
            editLink: false,
            editPathButtonType: 'ghost',
            editPathButtonText: '编辑',
            topArticle: false,
            publishTime: '',
            publishTimeType: 'immediately',

            editPublishTime: false, // 是否正在编辑发布时间
            classificationSelected: [], // 在所有分类目录中选中的目录数组
            classificationFinalSelected: [], // 最后实际选择的目录
            publishLoading: false,
            articleSource:'外部网页链接',
            previewUrl:''
        };
    },
    methods: {
        handleSearch(){
            this.searchProduct();
        },
        // 查询商品组
        inquiryProductGroup() {
        let searchOptions = { 
        };
        this.$http
            .post("/admin/inquiryProductGroup", this.common.request(searchOptions))
            .then(
            res => {
                if (res.data.body.status.statusCode == 0) {
                var data = res.data.body.data;
                this.groups = data.groups;
                }
            },
            res => {
            }
            );
        },
        searchProduct() {
            let keyArray = [];
            var searchOptions = {
                startIndex: this.startIndex,
                pageSize: this.pageSize
            };
            //判断是否有商品名称查询条件
            if (this.searchProductName) {
                keyArray.push("PRODUCT_NAME");
                searchOptions.productName = this.searchProductName;
            }
            searchOptions.keyArray = keyArray;
            this.$http
                .post("/admin/searchGroupBuyProduct", this.common.request(searchOptions))
                .then(
                response => {
                    if (response.data.body.status.statusCode == 0) {
                    this.products = response.data.body.data.groupBuys;
                    } else {
                    this.$Message.error(response.data.body.status.errorDesc);
                    }
                },
                response => {
                    this.$Message.error("失败，请稍后重试");
                }
                );
            },
        preview(){
            this.timestamp = new Date(+new Date()+8*3600*1000).toISOString().replace(/T/g,' ').replace(/\.[\d]{3}Z/,'')
            this.content1 = tinymce.activeEditor.getContent();
            this.previewCopywriting = true;
        },
        handleRemoveMateria (item) {
            let options = {
                actionType:'DELETE',
                materiaUuid:item.materiaUuid
            }
            this.$http.post("/admin/changeMateria", this.common.request(options)) 
            .then(response => {  
                if(response.data.body.status.statusCode==0){
                    this.initMateriaData();
                }else{
                    this.$Message.error(response.data.body.status.errorDesc);
                }
            }, response => {  
                this.$Message.error(response.data.body.status.errorDesc);
            })
        },
        handleSuccessMateria (res, file) {

            let url = res.data[0];  //获取上传成功后的地址
            let options = {
                actionType:'ADD',
                type:this.selectedType,
                url:url
            }
            this.$http.post("/admin/changeMateria", this.common.request(options)) 
            .then(response => {  
                if(response.data.body.status.statusCode==0){
                    this.initMateriaData();
                    
                }else{
                    this.$Message.error(response.data.body.status.errorDesc);
                }
            }, response => {  
                this.$Message.error(response.data.body.status.errorDesc);
            })
            
        },
        handleFormatErrorMateria (file) {
            this.$Notice.warning({
                title: 'The file format is incorrect',
                desc: 'File format of ' + file.name + ' is incorrect, please select jpg or png.'
            });
        },
        handleMaxSizeMateria (file) {
            this.$Notice.warning({
                title: 'Exceeding file size limit',
                desc: 'File  ' + file.name + ' is too large, no more than 2M.'
            });
        },
        handleBeforeUploadMateria () {
            const check = this.uploadList.length < 500;
            if (!check) {
                this.$Notice.warning({
                    title: 'Up to 500 pictures can be uploaded.'
                });
            }
            return check;
        },
        onCopy(){
            this.$Message.info('已复制');
        },
        selectMateria(){
            this.showMateria = true;
        },
        handleView (item) {
            this.viewArticle = item;
            this.visible = true;
        },
        handleRemove (item) {
            this.coverImageUrl = '';
        },
        handleSuccess (res, file) {
            debugger
            this.coverImageUrl = res.data[0];
            
        },
        handleFormatError (file) {
            this.$Notice.warning({
                title: '图片类型错误',
                desc: '不支持'+file.name + '图片类型, 请上传 jpg 或者 png图片.',
                duration:2
            });
        },
        handleMaxSize (file) {
            this.$Notice.warning({
                title: '图片大小超过限制',
                desc: '文件  ' + file.name + ' 图片超过10M.',
                duration:2
            });
        },
        handleBeforeUpload () {
            
        },
        save(){
            var linkType = '';
            let options = {
                actionType:'MODIFY',
                swiperUuid:this.swiper.swiperUuid,
                url:this.swiper.url
            };
            if(this.articleSource == '商品详情页'){
                options.linkType = 0;
                options.content = this.groupBuyProductUuid;
            }
            if(this.articleSource == '自定义内容'){
                options.linkType = 1;
                options.content = tinymce.activeEditor.getContent()
            }
            if(this.articleSource == '外部网页链接'){
                options.linkType = 2;
                options.content = this.previewUrl
            }
            if(this.articleSource == '商品组'){
                options.linkType = 3;
                options.content = this.groupUuid;
            }
            this.loading = true;
            this.$http.post("/admin/changeSwiper", this.common.request(options))  
                .then(response => {  
                    this.loading = false;
                    if(response.data.body.status.statusCode==0){
                        this.$Notice.success({
                            title: '成功',
                            desc: '轮播图链接内容已修改',
                            duration:2
                        });
                        this.$router.go(-1)
                    }else{
                        this.$Message.error(response.data.body.status.errorDesc);
                    }
                }, response => { 
                    this.loading = false;
                    this.$Message.error('出错了');
                    
                });
        },
        handleArticletitleBlur () {
            if (this.articleTitle.length !== 0) {
                // this.articleError = '';
                localStorage.articleTitle = this.articleTitle; // 本地存储文章标题
                if (!this.articlePathHasEdited) {
                    let date = new Date();
                    let year = date.getFullYear();
                    let month = date.getMonth() + 1;
                    let day = date.getDate();
                    this.fixedLink = window.location.host + '/' + year + '/' + month + '/' + day + '/';
                    this.articlePath = this.articleTitle;
                    this.articlePathHasEdited = true;
                    this.showLink = true;
                }
            } else {
                // this.articleError = '文章标题不可为空哦';
                this.$Message.error('文章标题不可为空');
            }
        },
        editArticlePath () {
            this.editLink = !this.editLink;
            this.editPathButtonType = this.editPathButtonType === 'ghost' ? 'success' : 'ghost';
            this.editPathButtonText = this.editPathButtonText === '编辑' ? '完成' : '编辑';
        },
        handleEditPublishTime () {
            this.editPublishTime = !this.editPublishTime;
        },
        handleSavePublishTime () {
            this.publishTimeType = 'timing';
            this.editPublishTime = false;
        },
        cancelEditPublishTime () {
            this.publishTimeType = 'immediately';
            this.editPublishTime = false;
        },
        setPublishTime (datetime) {
            this.publishTime = datetime;
        },
        setClassificationInAll (selectedArray) {
            this.classificationFinalSelected = selectedArray.map(item => {
                return item.title;
            });
            localStorage.classificationSelected = JSON.stringify(this.classificationFinalSelected); // 本地存储所选目录列表
        },
        setClassificationInOffen (selectedArray) {
            this.classificationFinalSelected = selectedArray;
        },
        canPublish () {
            if (this.articleTitle.length === 0) {
                this.$Message.error('请输入文章标题');
                return false;
            } else {
                return true;
            }
        },
        handlePreview () {
            if (this.canPublish()) {
                if (this.publishTimeType === 'immediately') {
                    let date = new Date();
                    let year = date.getFullYear();
                    let month = date.getMonth() + 1;
                    let day = date.getDate();
                    let hour = date.getHours();
                    let minute = date.getMinutes();
                    let second = date.getSeconds();
                    localStorage.publishTime = year + ' 年 ' + month + ' 月 ' + day + ' 日 -- ' + hour + ' : ' + minute + ' : ' + second;
                } else {
                    localStorage.publishTime = this.publishTime; // 本地存储发布时间
                }
                localStorage.content = tinymce.activeEditor.getContent();
                this.$router.push({
                    name: 'preview'
                });
            }
        },
        handleSaveDraft () {
            if (!this.canPublish()) {
                //
            }
        },
        handlePublish () {
            if (this.canPublish()) {
                this.publishLoading = true;
                setTimeout(() => {
                    this.publishLoading = false;
                    this.$Notice.success({
                        title: '保存成功',
                        desc: '文章《' + this.articleTitle + '》保存成功'
                    });
                }, 1000);
            }
        },
        initArticleData () {
            //编辑模式
            let articleUuid = this.$route.query.articleUuid;
            if(articleUuid!=null && articleUuid != ''){
                this.editModel=true;
                this.$http.post("/public/inquiryArticle", this.common.request({articleUuid:articleUuid}))  
                    .then(response => {  
                        if(response.data.body.status.statusCode==0){
                            this.article = response.data.body.data;
                            this.articleTitle=this.article.title;
                            this.coverImageUrl = this.article.coverImageUrl;
                            this.previewUrl=this.article.previewUrl;
                            if(this.previewUrl==null||this.previewUrl==''){
                                this.articleSource = '自定义内容';
                            }
                            tinymce.activeEditor.setContent(this.article.content);
                        }else{
                            this.$Message.error(response.data.body.status.errorDesc);
                        }
                    }, response => {  
                        this.$Message.error(response.data.body.status.errorDesc);
                    });
                }
        }
    },
    computed: {
        completeUrl () {
            let finalUrl = this.fixedLink + this.articlePath;
            localStorage.finalUrl = finalUrl; // 本地存储完整文章路径
            return finalUrl;
        }
    },
    mounted () {
        this.swiper = this.$route.query.Row;
        if (this.swiper.linkType == '0') {
            this.articleSource = '商品详情页';
            this.groupBuyProductUuid = this.swiper.content;
        }else{
            this.searchProduct();
        }
        if (this.swiper.linkType == '2') {
            this.articleSource = '外部网页链接';
            this.previewUrl = this.swiper.content
        }
        if (this.swiper.linkType == '3') {
            this.articleSource = '商品组';
            this.groupUuid = this.swiper.content
        }
        this.inquiryProductGroup();
        let initArticleDataFun = this.initArticleData;
        tinymce.init({
            selector: '#articleEditor',
            branding: false,
            elementpath: false,
            width:450,
            height: 600,
            language: 'zh_CN.GB2312',
            menubar: 'edit insert view format table tools',
            theme: 'modern',
            plugins: [
                'advlist autolink lists link image charmap print  hr anchor pagebreak imagetools',
                'searchreplace visualblocks visualchars code fullscreen fullpage',
                'insertdatetime media nonbreaking save table contextmenu directionality',
                'emoticons paste textcolor colorpicker textpattern imagetools codesample'
            ],
            toolbar1: ' newnote print fullscreen  undo redo | insert | styleselect | fontsizeselect | forecolor backcolor bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image emoticons media',
            autosave_interval: '20s',
            image_advtab: true,
            table_default_styles: {
                width: '100%',
                borderCollapse: 'collapse'
            },
            init_instance_callback:function (editor) {
                initArticleDataFun();                      
            },
        });
        if (this.swiper.linkType == '1') {
            this.articleSource = '自定义内容';
            tinymce.activeEditor.setContent(this.swiper.content);
        }
        
    },
    created() {
    this.swiper = this.$route.query.Row;
    this.coverImageUrl = this.$route.query.Row.url;
    
  },
    destroyed () {
        tinymce.get('articleEditor').destroy();
        // tinymce.activeEditor.setContent('');
    }
};
</script>
<style>
    .demo-upload-list{
        display: inline-block;
        width: 200px;
        //height: 160px;
        text-align: center;
        line-height: 60px;
        //border: 1px solid transparent;
        //border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        //box-shadow: 0 1px 1px rgba(0,0,0,.2);
        margin-right: 40px;
    }
    .demo-upload-list img{
        width: 100%;
        height: 100%;
    }
    .demo-upload-list-cover{
        display: none;
        position: absolute;
        top: 0;
        bottom: 60px;
        left: 0;
        right: 0;
        background: rgba(0,0,0,.6);
    }
    .demo-upload-list:hover .demo-upload-list-cover{
        display: block;
    }
    .demo-upload-list-cover i{
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 60px 2px 0 2px;
    }
</style>